package com.metadata_system.common.service;

import com.metadata_system.common.http.response_dto.TokenResponse;
import com.metadata_system.common.db.entity.AuthToken;
import com.metadata_system.common.db.mapper.AuthTokenMapper;
import com.metadata_system.common.dto.JwtToken;
import com.metadata_system.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
@Slf4j
public class TokenValidate {
    @Autowired(required = false)
    AuthTokenMapper authTokenMapper;
    @Autowired
    AuthTokenRepo authTokenRepo;
    @Autowired
    JwtUtil jwtUtil;
    // 检查 token 是否有效
    public JwtToken checkToken(HttpServletRequest request) {
        String authorizationString = request.getHeader("Authorization");
        String deviceIdString = request.getHeader("DeviceId");
        String platformString = request.getHeader("Platform");
//        log.info("authorizationString: "+authorizationString);
//        log.info("userTypeString: "+userTypeString);
//        log.info("deviceIdString: "+deviceIdString);
//        log.info("platformString: "+platformString);

        if (StringUtils.isEmpty(authorizationString) || StringUtils.isEmpty(deviceIdString)){
            log.info("token 验证失败 头部信息不全");
            return null;
        }
        return checkToken(authorizationString,platformString);
    }

    public JwtToken checkToken(String authorizationString,String platformString){
        // 1.获取请求参数
        String[] tokenStringArr=authorizationString.split(TokenResponse.builder().build().getTokenType());
        String jwtToken=null;
        if (tokenStringArr.length==1){
            jwtToken=tokenStringArr[0];
        }
        if (tokenStringArr.length==2){
            jwtToken=tokenStringArr[1];
        }
        if (jwtToken==null){
            log.info("token 验证失败 0");
            return null;
        }


        // 2.Jwt 格式,有效期验证
        if (!this.jwtUtil.validateToken(jwtToken)) {
            log.info("token 验证失败 1");
            return null;
        }
        // 3.获取 Jwt 数据
        Claims claims = this.jwtUtil.getClaimsFromToken(jwtToken);
        if (claims == null) {
            log.info("token 解析失败 3");
            return null;
        }
        String id = claims.get("id", String.class);
        String claimsTokenId = claims.get("tokenId", String.class);
        String claimsRole = claims.get("role", String.class);
        String claimsUsername = claims.get("username", String.class);
        Integer params=0;
        try {
            params = claims.get("params", Integer.class);
        }catch (Exception e){

        }
        if(StringUtils.isEmpty(claimsTokenId) || claimsRole==null || StringUtils.isEmpty(claimsUsername)){
            log.info("token 数据提取失败");
            return null;
        }


        // 5.可以换成 redis 读取
        AuthToken authToken=null;
        try {
            authToken = this.authTokenRepo.getByTokenId(JwtToken.decodeIDByString(id),platformString,claimsTokenId);
        }catch (Exception exception){
            return null;
        }
        if (authToken==null) {
            log.info("token 状态已经失效: "+authorizationString);
            log.info("tokenId: "+claimsTokenId);
            return null;
        }

        // 6.返回当前token对象
        return JwtToken.builder()
                .id(id)
                .jwtToken(jwtToken)
                .tokenId(claimsTokenId)
                .username(claimsUsername)
                .role(claimsRole)
                .params(params)
                .build();
    }
}
